package com.another.bidservice.service.impl;

import com.another.bidservice.dao.jpa.PlanProductJPADao;
import com.another.bidservice.dao.mapper.PlanProductDao;
import com.another.bidservice.entity.TPlan;
import com.another.bidservice.dao.jpa.PlanJPADao;
import com.another.bidservice.dao.mapper.PlanDao;
import com.another.bidservice.entity.TPlanProduct;
import com.another.bidservice.service.IPlanService;
import com.another.common.enums.CodeRuleEnum;
import com.another.common.enums.Enums;
import com.another.common.utils.common.DateUtil;
import com.another.common.utils.common.DecimalUtil;
import com.another.common.utils.common.EmptyUtil;
import com.another.common.utils.common.MyException;
import com.another.common.utils.result.Result;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class PlanServiceImpl extends BaseServiceImpl implements IPlanService {

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private PlanDao planDao;

    @Autowired
    private PlanJPADao planJPADao;

    @Autowired
    private PlanProductJPADao planProductJPADao;

    @Autowired
    private PlanProductDao planProductDao;

    @Override
    public Result getList(TPlan tPlan) {
        String sql = "select * from test_plan.t_plan";
        List<TPlan> list = planDao.getList(sql);

        List<TPlanProduct> products = planProductJPADao.findAllByPlanNoIn(list.stream().map(TPlan::getPlanNo).collect(Collectors.toList()));

        list.stream().forEach(i->{

            i.setProducts(new ArrayList<TPlanProduct>());

            products.stream().forEach(x->{
                if (EmptyUtil.isNotEmpty(x.getPlanNo()) && i.getPlanNo().equals(x.getPlanNo())) {
                    i.getProducts().add(x);
                }
            });
        });

        if (EmptyUtil.isEmpty(list)) {
            return Result.success("没有查询到数据！", "");
        } else {
            return Result.success(list);
        }
    }


    @Override
    public Result insertList(List<TPlan> tPlans) {
        int ret = planDao.insertList(tPlans);
        if (ret == tPlans.size()) {
            return Result.success("添加成功！", "");
        } else {
            throw new MyException(101, "添加失败！");
        }
    }


    @Override
    public Result deleteList(List<Integer> rowid) {
        int ret = planDao.deleteList(rowid);
        if (ret == rowid.size()) {
            return Result.success("删除成功！", "");
        } else {
            throw new MyException(101, "删除失败！");
        }
    }

    @Override
    public Result updateList(List<TPlan> tPlans) {
        try {
            int ret = planDao.updateList(tPlans);
            return Result.success("修改成功！", "");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "修改失败！");
        }
    }


    @Override
    public Result insertPlan(TPlan plan) {
        try {

            if (EmptyUtil.isEmpty(plan.getShipName())) {
                return Result.error("请选择货主！");
            }

            if (EmptyUtil.isEmpty(plan.getProducts())) {
                return Result.error("请输入货物信息！");
            }

            if (EmptyUtil.isEmpty(plan.getTransType())) {
                return Result.error("请选择运输类型！");
            }

            if (EmptyUtil.isEmpty(plan.getProxyType())) {
                return Result.error("请选择代理模式！");
            }

            if (EmptyUtil.isEmpty(plan.getStartPoint())) {
                return Result.error("请输入起店码头信息！");
            }

            if (EmptyUtil.isEmpty(plan.getProxyType())) {
                return Result.error("请输入终点码头信息！");
            }

            plan.setPlanStatus(Enums.PlanStatus.INITIAL.getCode());
            plan.setCreateId(plan.getRequestUserId());
            plan.setCreateDate(DateUtil.getNowDateByyyyyMMddHHmmss());
            plan.setWeight("0");

            //生成货盘编号
            String planNo = generateNumber(CodeRuleEnum.PENDING_PALLET_NUMBER.getCode());
            plan.setPlanNo(planNo);

            //生成货物编号
            String nos = generateNumber(CodeRuleEnum.PRODUCT_NUMBER.getCode(),plan.getProducts().size());
            List<String> prodNos = new ArrayList<>(Arrays.asList(nos.split(",")));

            plan.getProducts().stream().forEach(i -> {

                plan.setWeight(DecimalUtil.add(plan.getWeight(),i.getWeight()));

                i.setProductNo(prodNos.get(0));
                prodNos.remove(0);
                i.setCreateDate(DateUtil.getNowDateByyyyyMMddHHmmss());
                i.setCreateId(plan.getRequestUserId());
                i.setPlanNo(planNo);
            });


            //保存货物信息
            planProductJPADao.saveAll(plan.getProducts());
            planJPADao.save(plan);


            return Result.success("添加成功！",plan);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "添加失败！");
        }
    }

    @Override
    public Result updatePlan(TPlan plan) {
        try {

            if (EmptyUtil.isNotEmpty(plan.getProducts())) {
                plan.setWeight("0");
                plan.getProducts().stream().forEach(i->{
                    plan.setWeight(DecimalUtil.add(plan.getWeight(),i.getWeight()));
                    i.setCreateId(plan.getRequestUserId());
                });
                planProductDao.updateList(plan.getProducts());
            }

            plan.setUpdateId(plan.getRequestUserId());

            int ret = planDao.updatePlan(plan);
            return Result.success("修改成功！",plan);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "修改失败！");
        }
    }

    @Override
    public Result deletePlan(TPlan tPlan) {
        try {
            int ret = planDao.deletePlan(tPlan);
            return Result.success("删除成功！", "");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "删除失败！");
        }
    }
}



